from datetime import *
from core.models import Webcam, Image
import sharding
from sharding import helper, static
import core.utils as utils
from django.db import connection, transaction
from mturk.tagging import finder


def fetch_all_cams(k):
	# We need to first connect to the database and fetch all the IDs
	cursor = connection.cursor()

	# set query string
	qs = """SELECT id, last_captured, url FROM core_webcam"""
	cursor.execute(qs)
	webcam_data = cursor.fetchall()

	result = []
	for i in xrange(k):
		webcam = webcam_data[i]
		id = webcam[0]
		last_captured = webcam[1]
		url = webcam[2]
		good = cam_filter(id)
		if good:
			result.append(id)

	print "found %s good cams in %s total cams!" % (len(result), k)
	with open("ids.txt", "wb") as f:
		for each in result:
			f.write("%s\n"%each)
	f.close()

def cam_filter(id):
	print("Examining camera %s..." % id)
	# we filter out bad cams by looking at number of images captured the past 100 days
	today = finder.fix_dt(date.today())
	lastyear_today = finder.fix_dt(date.today() - timedelta(days=100))

	# this turns out to be too slow, use the helper function
	imgs = Image.images.getImagesInRange(lastyear_today, today, camera=id)
	#count = count_imgs(id, lastyear_today, today)
	count = len(imgs)
	if count > 100:
		print("%s images...good\n"%count)
	else:
		print("%s images...bad\n"%count)
	# only good when it has more than 100 images from the past 100 days
	return count > 100

def count_imgs(id, start, end):

	start_time = start.time()
	end_time = end.time()
	start_date = start.date()
	end_date = end.date()

	time_format = '%H:%M'
	start_time_str = start_time.strftime(time_format)
	end_time_str   =   end_time.strftime(time_format)

	date_format = '%Y-%m-%d'
	start_date_str = start_date.strftime(date_format)
	end_date_str = end_date.strftime(date_format)

	shard_names = []

	start = start_date
	month = start.month
	year = start.year

	#get a list of shard names from the timespan
	while finder.fix_dt(start) <= finder.fix_dt(end_date):
		shard_names.append(sharding.helper.convertTimestampToShardName(start))
		if month == 12:
			month = 1
			year = year + 1
		else:
			month = month + 1

		start = datetime(year, month, 1)

	qs = ""
	#construct the query string
	for shard_name in shard_names:
		qs = qs + """SELECT * FROM """ + shard_name + """ WHERE webcam_id = %s AND DATE(timestamp) BETWEEN '%s' AND '%s' AND TIME(timestamp) BETWEEN '%s' AND '%s'""" % (id, start_date_str, end_date_str, start_time_str, end_time_str)

		if shard_name != shard_names[-1]:
			qs = qs + """ UNION ALL """

	qs += ' ORDER BY timestamp'
	#execute the query and get the result
	cursor = connection.cursor()
	cursor.execute(qs)

	count = 0
	for row in cursor.fetchall():
		count += 1

	return count


def print_to_file(string, filename):
	with open(filename, 'w') as f:
		f.write(string)
	f.close()

def read_from_file(filename):
	with open(filename, 'r') as f:
		for line in f:
			print line
	f.close()